package net.rock.eshop.service;

import net.rock.eshop.entity.User;
import net.rock.eshop.mapper.UserMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public User fetchUserById(int id) {
        return userMapper.fetchUserById(id);
    }

    public User fetchUserByName(String name) {
        return userMapper.fetchUserByName(name);
    }

    public User fetchUserBySessionId(String sessionId) {
        return userMapper.fetchUserBySessionId(sessionId);
    }

    public void register(User user) {
        userMapper.register(user);
    }

    // 返回SessionID
    public Optional<String> login(String username, String password, int permission) {
        User user = fetchUserByName(username);

        if (user == null || !password.equals(user.getPassword()) || permission > user.getPermission()) {
            return Optional.empty();
        } else {
            Date now = new Date();
            String sessionId = DigestUtils.md5Hex(username + now);
            userMapper.logoutAll(user.getId());
            userMapper.login(sessionId, user.getId());  // write session into db
            return Optional.of(sessionId);
        }
    }

    public void logout(String sessionId) {
        userMapper.logout(sessionId);
    }
}
